package com.example.demo.controller;

import com.example.demo.model.ChatRequest;
import com.example.demo.service.SparkAIService;
import com.example.demo.service.AIChatSessionService;
import com.example.demo.service.ProductService;
import com.example.demo.util.Result;
import com.example.demo.vo.ProductVO;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.ArrayList;
import lombok.Data;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/api/ai")
public class AIController {
    private final SparkAIService sparkAIService;
    private final AIChatSessionService sessionService;
    private final ProductService productService;

    public AIController(SparkAIService sparkAIService, AIChatSessionService sessionService, ProductService productService) {
        this.sparkAIService = sparkAIService;
        this.sessionService = sessionService;
        this.productService = productService;
    }

    @PostMapping("/chat")
    public Result<Object> chat(@RequestBody Map<String, String> params) {
        try {
            String message = params.get("message");
            if (message == null || message.trim().isEmpty()) {
                return Result.error("消息不能为空");
            }

            String sessionId = sessionService.createSession();
            String reply = sparkAIService.chat(sessionId, message).get(30, TimeUnit.SECONDS);
            log.info("收到AI回复: {}", reply);

            try {
                // 提取商品ID和推荐理由
                int productId;
                String recommendReason;
                
                // 首先尝试提取商品ID
                if (reply.contains("推荐商品ID：")) {
                    String[] parts = reply.split("推荐商品ID：");
                    // 提取ID部分，可能包含换行符
                    String idPart = parts[1].split("\n")[0].trim();
                    // 只保留数字
                    productId = Integer.parseInt(idPart.replaceAll("[^0-9]", ""));
                    
                    // 然后尝试提取推荐理由
                    if (reply.contains("推荐理由：")) {
                        String[] reasonParts = reply.split("推荐理由：");
                        recommendReason = reasonParts[1].trim();
                    } else if (reply.contains("详细说明：")) {
                        String[] detailParts = reply.split("详细说明：");
                        recommendReason = detailParts[1].trim();
                    } else {
                        // 如果没有找到推荐理由或详细说明，使用默认文本
                        recommendReason = "为您推荐以下商品";
                    }
                } else {
                    log.warn("无法识别的AI回复格式: {}", reply);
                    return Result.error("AI回复格式不正确");
                }
                
                log.info("解析到的商品ID: {}, 推荐理由: {}", productId, recommendReason);
                
                // 获取商品信息
                List<ProductVO> products = productService.getProductDetail(productId);
                
                if (products != null && !products.isEmpty()) {
                    Map<String, Object> data = new HashMap<>();
                    data.put("reason", recommendReason);
                    data.put("products", products);
                    log.info("返回的商品数据: {}", data);
                    return Result.success(data);
                } else {
                    log.warn("未找到商品信息, productId: {}", productId);
                    return Result.error("未找到商品信息");
                }
            } catch (Exception e) {
                log.error("解析AI回复失败: {}, 原始回复: {}", e.getMessage(), reply);
                return Result.error("解析回复失败：" + e.getMessage());
            }
        } catch (Exception e) {
            log.error("处理请求失败: {}", e.getMessage(), e);
            return Result.error("处理请求失败: " + e.getMessage());
        }
    }
}

